package com.ks.controller;

import com.ks.base.BaseAction;
import com.ks.entity.*;
import com.ks.service.DepositoryService;
import com.ks.service.PaperQuestionService;
import com.ks.service.PaperQuestiontypeService;
import com.ks.service.PaperService;
import com.ks.util.HtmlUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author youniwo
 */
@Controller
@RequestMapping("/paper")
public class PaperMngController extends BaseAction {

    private final static Logger log = Logger.getLogger(PaperMngController.class);

    // Servrice start
    @Autowired(required = false)
    private PaperService<Paper> paperService;
    @Autowired(required = false)
    private DepositoryService<Depository> depositoryService;
    @Autowired(required = false)
    private PaperQuestiontypeService<PaperQuestiontype> paperQuestiontypeService;
    @Autowired(required = false)
    private PaperQuestionService<PaperQuestion> paperQuestionService;

    /**
     * 试卷管理总页面
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/pagedata")
    public ModelAndView list(Paper entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        return forword("/pages/paper/paper-list", context);
    }

    /**
     * 创建/修改试卷内容页面
     *
     * @param paperid
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/viewOrEdit")
    public ModelAndView viewOrEdit(String paperid, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();

        context = paperService.viewOrEditPage(paperid);

        return forword("/pages/paper/paper-view", context);
    }

    /**
     * 预览试卷内容页面
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/pagePreview")
    public ModelAndView pagePreview(String id, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        Map<String, Object> map = new HashMap<>();
        context = paperService.pagePreview(id);
        return forword("/pages/paper/paper-view", context);
    }
    /**
     * 预览试卷内容页面
     *
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/printPreview")
    public ModelAndView printPreview(String id, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        String answer = request.getParameter("answer");
        context = paperService.printPreview(id);
        context.put("answer",answer);
        return forword("/pages/paper/print-view", context);
    }
    /**
     * 创建/修改试卷基本信息第一步页面
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/addOrEdit")
    public ModelAndView addOrEdit(Paper entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        List<Depository> list = depositoryService.queryContents(null);
        if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
            context.put("title", "新建试卷");
        } else {
            Paper paper = paperService.queryById(entity);
            context.put("title", "编辑试卷");
            context.put("paper", paper);
        }
        context.put("list", list);
        System.out.println(list);
        return forword("/pages/paper/paper-add-basic", context);
    }

    /**
     * 创建/修改试卷基本信息第二步页面 手动
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/handdeploy")
    public ModelAndView handdeploy(Paper entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        context = paperService.deployPaper(entity);
        return forword("/pages/paper/paper-add-deploy-hand", context);
    }

    /**
     * 添加或修改数据paperquestion表  手动组卷
     *
     * @param entity
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/updatePaperQuestions")
    @ResponseBody
    public ModelAndView updatePaperQuestions(Paper entity, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> context = getRootMap();
        String paperid = request.getParameter("paperid");
        String qutypeid = request.getParameter("qutypeid");
        entity.setId(Integer.parseInt(paperid));
        paperService.updatePaperQuestions(paperid, qutypeid);
        context = paperService.deployPaper(entity);

        return forword("/pages/paper/paper-add-deploy-hand", context);
    }

    /**
     * 创建/修改试卷基本信息第二步页面 自动
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/autodeploy")
    public ModelAndView autodeploy(Paper entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        context = paperService.deployPaperAuto(entity);
        return forword("/pages/paper/paper-add-deploy", context);
    }

    /**
     * 创建/修改试卷基本信息第三步页面
     *
     * @param entity
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/issue")
    public ModelAndView issue(Paper entity, HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();

        String paperid = request.getParameter("paperid");

        context = paperService.issuePage(paperid);

        return forword("/pages/paper/paper-add-issue", context);
    }

    /**
     * 跳转到查看某个类型的题页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("toCheckQuestion")
    public ModelAndView toCheckQuestion(HttpServletRequest request) throws Exception {
        Map<String, Object> context = getRootMap();
        String ConId = request.getParameter("ConId");
        String paperid = request.getParameter("paperid");
        String score = request.getParameter("score");
        //paper_questiontype表 questiontypeid
        String questiontypeId = request.getParameter("questiontypeId");
        context = paperService.toCheckQuestion(ConId, questiontypeId, paperid, score);
        context.put("paperid", paperid);
        context.put("contentid", ConId);
        context.put("typeId", questiontypeId);
        return forword("/pages/paper/item-view", context);
    }

    /**
     * 试卷发布成功
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/doneIssue")
    public void doneIssue(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> context = getRootMap();
        String paperid = request.getParameter("paperid");
        context.put("status", "1");
        //试卷备份
        paperService.paperCopy(paperid);
        HtmlUtil.writerJson(response, context);
    }

    /**
     * ilook 首页
     *
     * @param entity
     * @param response
     * @throws Exception
     */
    @RequestMapping("/dataList")
    public void datalist(Paper entity, HttpServletResponse response) throws Exception {

        List<Paper> list = paperService.findAll(null);
        for (Paper paper : list) {
            Date date = paper.getCreatetime();
            DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            paper.setCreatetimeStr(format1.format(date));
            paper.setCount(paperQuestionService.queryListByPaperId(paper.getId()));
        }
        HtmlUtil.writerJson(response, list);
    }

    /**
     * 添加或修改数据paper表
     * @param entity
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/save")
    @ResponseBody
    public void save(Paper entity, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession session = request.getSession(true);
        User user = (User) session.getAttribute("userInfo");
        String arr = request.getParameter("extend");
        entity.setUpdatetime(new Date());
        entity.setUpdater(user.getId());
        entity.setExtend(arr);
        if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
            entity.setCreatetime(new Date());
            entity.setCreater(user.getId());
            paperService.add(entity);
        } else {
            paperService.updateBySelective(entity);
        }
        HtmlUtil.writerJson(response, entity);
    }

    /**
     * 添加或修改数据paperquestiontype表
     * 自动生成考试试卷
     *
     * @param list
     * @param typeIds
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/saveType")
    @ResponseBody
    public void saveType(@RequestBody List<PaperQuestiontype> list, Integer[] typeIds, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {
        PaperQuestiontype enti = list.get(0);
        paperQuestionService.deleteByPaperid(enti.getPaper_id());
        Map<String, Object> context = paperService.saveOrEditPaper(list);

        HtmlUtil.writerJson(response, context);
    }

    /**
     * 添加或修改数据paperquestiontype表
     *
     * @param list
     * @param typeIds
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/handsaveType")
    @ResponseBody
    public void handsaveType(@RequestBody List<PaperQuestiontype> list, Integer[] typeIds, HttpServletRequest request,
                             HttpServletResponse response) throws Exception {

        paperService.saveOrEditPaperHand(list);
        sendSuccessMessage(response, "保存成功~");
    }

    @RequestMapping("/getId")
    public void getId(String id, HttpServletResponse response) throws Exception {
        Map<String, Object> context = new HashMap<>();
        Paper entity = paperService.queryById(id);
        if (entity == null) {
            sendFailureMessage(response, "没有找到对应的记录!");
            return;
        }
        context.put(SUCCESS, true);
        context.put("data", entity);
        HtmlUtil.writerJson(response, context);
    }

    @RequestMapping("/delpapertype")
    public void del(PaperQuestiontype entity, HttpServletResponse response) throws Exception {

        paperQuestiontypeService.del(entity);

        sendSuccessMessage(response, "删除成功");
    }

    @RequestMapping("/delpaper")
    public void del(Paper entity, HttpServletResponse response) throws Exception {

        paperService.delpaper(entity);

        sendSuccessMessage(response, "删除成功");
    }

    /**
     * 分页查询试题
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("toCheckQuestionAjax")
    @ResponseBody
    public Map<String, Object> toCheckQuestionAjax(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String typeId = request.getParameter("typeId");
        String ConId = request.getParameter("ConId");
        String paperid = request.getParameter("paperid");
        String ids = request.getParameter("ids");
        String page_num = request.getParameter("page_num");
        String page_size = request.getParameter("page_size");
        return paperService.toCheckQuestionAjax(paperid, typeId, ConId, page_num, page_size);

    }

    /**
     * 分页查询试题
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("updatePaperQuestionsAjax")
    @ResponseBody
    public void updatePaperQuestionsAjax(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String type = request.getParameter("type");
        String paperid = request.getParameter("paperid");
        String questionid = request.getParameter("questionid");
        paperService.updatePaperQuestionsAjax(type,paperid,questionid);

    }

}
